package com.htfyun.fragment.settings;

import android.Manifest;
import android.content.Context;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.htfyun.fragment.base.BaseWithPageNumberAdapter;
import com.htfyun.fragment.base.BaseWithPageNumberFragment;
import com.htfyun.utils.DebugLog;
import com.htfyun.view.CustomGridLayoutManager;
import com.htfyun.wifilibrary.SecurityModeEnum;
import com.htfyun.wifilibrary.WiFiManager;
import com.htfyun.wifilibrary.listener.OnWifiConnectListener;
import com.htfyun.wifilibrary.listener.OnWifiEnabledListener;
import com.htfyun.wifilibrary.listener.OnWifiScanResultsListener;
import com.kongqw.permissionslibrary.PermissionsManager;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.geometerplus.zlibrary.ui.android.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by sst on 2018/1/26.
 */

public class SettingsWifiFragment extends BaseWithPageNumberFragment<ScanResult> {

    private SettingsWifiRecyclerViewAdapter adapter;

    List<ScanResult> scanResultListCache = new ArrayList<>();
    
    
    private TextView txtSSID;
    private EditText editPassword;
    
    private TextView txtConnectInfo;
    
    private TextView txtEmpty;
    private View layoutPassword;

    private Button cancel;
    private Button connect;

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };
    private final int GET_WIFI_LIST_REQUEST_CODE = 0;
    private PermissionsManager mPermissionsManager;


    public static SettingsWifiFragment newInstance() {

        Bundle args = new Bundle();

        SettingsWifiFragment fragment = new SettingsWifiFragment();
        fragment.setArguments(args);
        return fragment;
    }
    
    private WiFiManager mWiFiManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        
        mWiFiManager = WiFiManager.getInstance(getContext());

        // 动态权限管理器
        mPermissionsManager = new PermissionsManager(_mActivity) {
            @Override
            public void authorized(int requestCode) {
                // 6.0 以上系统授权通过
                if (GET_WIFI_LIST_REQUEST_CODE == requestCode) {
                    // 获取WIFI列表
                    getAdapter().notifyDataSetChanged();

                }
            }

            @Override
            public void noAuthorization(int requestCode, String[] lacksPermissions) {
                // 6.0 以上系统授权失败
            }

            @Override
            public void ignore() {
                // 6.0 以下系统 获取WIFI列表
                getAdapter().notifyDataSetChanged();
            }
        };
        // 请求WIFI列表
        mPermissionsManager.checkPermissions(GET_WIFI_LIST_REQUEST_CODE, PERMISSIONS);

        View view = super.onCreateView(inflater, container, savedInstanceState);

        View passwd = inflater.inflate(R.layout.htfyun_settings_wifi_empty_view, null);

        txtEmpty = (TextView) passwd.findViewById(R.id.txtEmpty);
        layoutPassword = passwd.findViewById(R.id.layoutPassword);
        layoutPassword.setVisibility(View.GONE);

        txtConnectInfo = (TextView) passwd.findViewById(R.id.txtConnectInfo);
                
        txtSSID = (TextView) passwd.findViewById(R.id.txtSSID);
        editPassword = (EditText) passwd.findViewById(R.id.editPassword);
        cancel = (Button) passwd.findViewById(R.id.cancel);
        connect = (Button) passwd.findViewById(R.id.connect);
        
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scanResultListCache.addAll(mWiFiManager.getScanResults());
                rebuildUI();
                hideSoftInput();

            }
        });
        
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String password = editPassword.getText().toString();
                if (TextUtils.isEmpty(password)) {
                    return;
                }

                ScanResult scanResult = (ScanResult)view.getTag();

                switch (mWiFiManager.getSecurityMode(scanResult)) {
                    case WPA:
                    case WPA2:
                      
                        mWiFiManager.connectWPA2Network(scanResult.SSID, password);
                        break;
                    case WEP:
                       
                        mWiFiManager.connectWEPNetwork(scanResult.SSID, password);
                        break;
                    case OPEN: // 开放网络
                        mWiFiManager.connectOpenNetwork(scanResult.SSID);
                        break;
                }

                txtConnectInfo.setText(R.string.wifi_connecting);
                hideSoftInput();

            }
        });
        
        
        setEmptyView(passwd);

        getAdapter().setOnItemClickListener(new SettingsWifiRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(ScanResult scanResult) {
                DebugLog.e("scanResult = " + scanResult);

                if (scanResult == null) {
                    return;
                }
                connect.setTag(scanResult);
                txtEmpty.setVisibility(View.GONE);
                layoutPassword.setVisibility(View.VISIBLE);

                txtSSID.setText(scanResult.SSID);
                editPassword.setText("");
                txtConnectInfo.setText("");
            
                scanResultListCache.clear();
                rebuildUI();
            }
        });

        getWifiEnableCheckBox().setVisibility(View.VISIBLE);
        getWifiEnableCheckBox().setChecked(mWiFiManager.isWifiEnabled());
        
        getWifiEnableCheckBox().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!checkEnable) {
                    return;
                }
                if (b) {
                    mWiFiManager.openWiFi();
                } else {
                    mWiFiManager.closeWiFi();
                }
            }
        });

        return view;
    }

    private boolean checkEnable = true;


    public void hideSoftInput(){
//        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        ((InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(_mActivity.getCurrentFocus().getWindowToken(), 
                        InputMethodManager.HIDE_NOT_ALWAYS); 
    }
    
    private OnWifiScanResultsListener scanResultsListener = new OnWifiScanResultsListener() {
        @Override
        public void onScanResults(List<ScanResult> scanResults) {

            scanResultListCache.clear();
            scanResultListCache.addAll(scanResults);
            rebuildUI();

            if (scanResults.size() == 0) {
                txtEmpty.setVisibility(View.VISIBLE);
                layoutPassword.setVisibility(View.GONE);
            }

            DebugLog.e("scanResults size = " + scanResults.size());

        }
    };
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        mWiFiManager.startScan();

        DebugLog.e("settings wifi onSupportVisible");

        

        mWiFiManager.registerWifiReceiver(_mActivity);
        mWiFiManager.setOnWifiScanResultsListener(scanResultsListener);

        mWiFiManager.setOnWifiEnabledListener(new OnWifiEnabledListener() {
            @Override
            public void onWifiEnabled(boolean enabled) {
                checkEnable = false;
                getWifiEnableCheckBox().setChecked(enabled);
                checkEnable = true;

                if (!enabled) {
                    scanResultListCache.clear();
                    rebuildUI();
                } else {

//                    scanResultListCache.clear();
//                    scanResultListCache.addAll(mWiFiManager.getScanResults());
//                    rebuildUI();

                    mWiFiManager.startScan();
//                    mWiFiManager.setOnWifiScanResultsListener(scanResultsListener);

                }
            }
        });
        
        mWiFiManager.setOnWifiConnectListener(new OnWifiConnectListener() {
            @Override
            public void onWiFiConnectLog(String log) {

                DebugLog.e("log = " + log);
                
            }

            @Override
            public void onWiFiConnectSuccess(String SSID) {
                String info = getString(R.string.wifi_ok_to_connect_ssid, SSID);
                txtConnectInfo.setText(info);

            }

            @Override
            public void onWiFiConnectFailure(String SSID) {
                String info = getString(R.string.wifi_fail_to_connect_ssid, SSID);
                txtConnectInfo.setText(info);

            }
        });

    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        
        DebugLog.e("settings wifi onSupportInvisible");

        mWiFiManager.unregisterWifiReceiver(_mActivity);
        mWiFiManager.setOnWifiScanResultsListener(null);

    }

    @Override
    public void rebuildUI() {

        if (getWifiEnableCheckBox().isChecked()) {
            txtEmpty.setText(R.string.wifi_not_found);
        } else {
            txtEmpty.setText(R.string.wifi_closed);
        }
        
        if (getTotalItemList().size() == 0) {
            setLayoutPageNumberVisibility(View.GONE);
            
        } else {
            setLayoutPageNumberVisibility(View.VISIBLE);
        }
        super.rebuildUI();
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new CustomGridLayoutManager(_mActivity, getItemCountPerPage(),
                LinearLayoutManager.HORIZONTAL, false);
    }

    @Override
    public RecyclerView.ItemDecoration getDecor() {
        return new HorizontalDividerItemDecoration.Builder(getContext())
                        .color(Color.BLACK)
                        .size(5)
                        .margin(10)
                        .build();
    }

    @Override
    public SettingsWifiRecyclerViewAdapter getAdapter() {
        if (adapter == null) {
            adapter = new SettingsWifiRecyclerViewAdapter(_mActivity, mWiFiManager);
        }
        return adapter; 
    }

    @Override
    public int getItemCountPerPage() {
        return getContext().getResources().getInteger(R.integer.wifi_item_count_per_page);
    }

    @Override
    public List<ScanResult> getTotalItemList() {
        return scanResultListCache;
    }

    @Override
    public String getStringForTextEmpty() {
        return "";
    }

    /**
     * Android 6.0 权限校验
     *
     * @param requestCode  requestCode
     * @param permissions  permissions
     * @param grantResults grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 复查权限
        mPermissionsManager.recheckPermissions(requestCode, permissions, grantResults);
    }
   
}
